package ui.fragment.intersionfragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import application.App;
import base.BaseBean;
import base.fragment.BaseNetFragment;
import event.IntersionEvent;
import jp.wasabeef.richeditor.RichEditor;
import student.andlei.com.student.R;
import ui.activity.AddWacomActivity;
import utils.QiniuUploadUtils;
import utils.SPUtils;

/**
 * author : ChenHuiMing
 * date : 2018/9/27
 * email : 907399255@qq.com
 * description : 追问
 */
public class IntersionAskedFragment extends BaseNetFragment {
    public static final String SUPER_ADD_QA = "/Qa/superaddQa";

    private RichEditor mEtProblem;
    private TextView mTvSubmit;
    private int mQaId;

    public static IntersionAskedFragment getInstance() {
        return new IntersionAskedFragment();
    }

    @Override
    public void success(String action, BaseBean baseBean) {
        if (TextUtils.equals(action, SUPER_ADD_QA) && baseBean.code == 200) {
            mEtProblem.setHtml("");
            IntersionEvent pageEvent = new IntersionEvent();
            pageEvent.rightPager = 0;
            pageEvent.isRightPage = true;
            pageEvent.isRefresh = true;
            pageEvent.qa_id = mQaId;
            EventBus.getDefault().post(pageEvent);
        }
    }

    @Override
    public void error(String action, Throwable e) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_intersion_asked;
    }

    @Override
    protected void findViews() {
        mEtProblem = getView(R.id.et_problem);
        mTvSubmit = getView(R.id.tv_submit);
    }

    @Override
    protected void formatViews() {
        initRichEditor();
        EventBus.getDefault().register(this);
        getView(R.id.iv_picture).setOnClickListener(this);
        getView(R.id.iv_camera).setOnClickListener(this);
        getView(R.id.iv_drawingboard).setOnClickListener(this);
        getView(R.id.tv_back).setOnClickListener(this);
        getView(R.id.tv_submit).setOnClickListener(this);
    }

    private void initRichEditor() {
        mEtProblem.setEditorFontSize(18);
        mEtProblem.setPlaceholder("请输入您要提问的问题");
        mEtProblem.setEditorFontColor(getResources().getColor(R.color.font_black));
        mEtProblem.setPadding(10, 10, 10, 10);
    }

    @Override
    protected void formatData() {

    }

    @Override
    protected void getBundle() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                IntersionEvent pageEvent = new IntersionEvent();
                pageEvent.rightPager = 0;
                pageEvent.isRightPage = true;
                EventBus.getDefault().post(pageEvent);
                break;
            case R.id.iv_picture:
                mEtProblem.focusEditor();
                openPhoto();
                break;
            case R.id.iv_camera:
                mEtProblem.focusEditor();
                openCamera();
                break;
            case R.id.iv_drawingboard:
                mEtProblem.focusEditor();
                jumpTo(AddWacomActivity.class, 0);
                break;
            case R.id.tv_submit:
                if (TextUtils.isEmpty(mEtProblem.getHtml())) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.want_ask_hint), Toast.LENGTH_LONG).show();
                    return;
                }
                Map<String, Object> map = new HashMap<>();
                map.put("qa_id", mQaId);
                map.put("content", mEtProblem.getHtml());
                post(SUPER_ADD_QA, map, BaseBean.class, false);
                mEtProblem.setHtml("");
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(IntersionEvent event) {
        if (event.isRightPage && event.rightPager == 2) {
            mQaId = event.qa_id;
        }
    }

    private List<LocalMedia> selectList = new ArrayList<>();

    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                case PictureConfig.REQUEST_CAMERA:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = selectList.get(0);
                    String compressPath = localMedia.getCompressPath();

                    String qiniutoken = SPUtils.getInstance(App.getInstance()).getString("uptoken");
                    String key = System.currentTimeMillis() + "note.png";
                    QiniuUploadUtils.getInstance().uploadFile(compressPath, new QiniuUploadUtils.UploadListener() {
                        @Override
                        public void onUploadSuccess(String key) {
                            String yuming = SPUtils.getInstance(getActivity()).getString("domain");
                            final String image = yuming + key;
                            mEtProblem.insertImage(image, "\" style=\"max-width:100%");
                            selectList.clear();
                        }

                        @Override
                        public void onUploadFail(Error error) {
                            toast("插入图片失败");
                        }
                    }, qiniutoken);
                    break;
            }
        } else if (requestCode == 0) {
            if (data != null) {
                QiniuUploadUtils.getInstance().uploadFile(data.getStringExtra("filename"), new QiniuUploadUtils.UploadListener() {
                    @Override
                    public void onUploadSuccess(String key) {
                        hideLoadDialog();
                        String yuming = SPUtils.getInstance(getActivity()).getString("domain");
                        final String image = yuming + key;
                        mEtProblem.insertImage(image, "\" style=\"max-width:100%");
                    }

                    @Override
                    public void onUploadFail(Error error) {
                        hideLoadDialog();
                        Looper.prepare();
                        toast("插入图片失败");
                        Looper.loop();
                    }
                }, SPUtils.getInstance(getActivity()).getString("uptoken"));
            }

        }
    }

    private void openPhoto() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(false)
                .enableCrop(false)
                .compress(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .isGif(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void openCamera() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(false)
                .compress(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .isGif(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .selectionMedia(selectList)
                .forResult(PictureConfig.REQUEST_CAMERA);
    }
}
